<template>
  <div class="contrainer">
    <!-- 导航栏 -->
    <el-tabs>
      <el-tab-pane label="统计">
        <div class="content" ref="printStatistics">
          <!-- 标题 -->
          <p class="title">{{ survey.surveyName }}</p>
          <div class="questions">
            <div
              v-for="(item, index) in survey.questionList"
              :key="index"
              class="item"
            >
              <p class="itemtitle">
                <span>{{ index + 1 }}、</span>
                <span v-html="item.questionName"></span>
                <span class="type">【{{ types[item.questionType - 1] }}】</span>
              </p>
              <!-- 单选或者多选 -->
              <div v-if="item.questionType == 1 || item.questionType == 2">
                <el-table
                  :data="item.optionList"
                  border
                  show-summary
                  :summary-method="getSummaries"
                  style="width: 100%; margin-top: 20px"
                >
                  <el-table-column prop="title" label="选项" sortable>
                    <template slot-scope="scope">
                      <div style="display: flex">
                        <div v-if="!scope.row.optionName == ''">
                          {{ scope.row.optionName }}
                        </div>
                        <img
                          :src="scope.row.optionPicUrl"
                          alt=""
                          style="height: 40px"
                          v-if="scope.row.optionPicUrl"
                        />
                      </div>

                      <span
                        v-if="scope.row.fillFlag === 1"
                        style="color: blue"
                        @click="lookmsg(scope.row, 2, index)"
                        >[详情]</span
                      >
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="answerNum"
                    label="小计"
                    sortable
                    width="120"
                    align="center"
                  >
                  </el-table-column>
                  <el-table-column prop="proportion" label="比例">
                    <template slot-scope="scope">
                      <el-progress
                        :percentage="scope.row.answerRate"
                        color="#2eb791"
                        stroke-linecap="square"
                      ></el-progress>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <!-- 填空题 -->
              <div v-if="item.questionType == 3">
                <el-button plain @click="lookmsg(item, 1, index)"
                  >详细作答情况</el-button
                >
              </div>
              <!-- 简答题 -->
              <div v-if="item.questionType == 4">
                <el-button plain @click="lookmsg(item, 1, index)"
                  >详细作答情况</el-button
                >
              </div>
            </div>
          </div>
          <div class="loadbtns">
            <el-button type="primary" @click="printStatistics">打印</el-button>
            <el-button type="primary" @click="downLoadWord">下载</el-button>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="答卷">
        <div @click="searchBytips" class="fifter">
          <i class="el-icon-s-data"></i>
          筛选条件
          <i class="el-icon-caret-bottom"></i>
        </div>
        <div class="content" ref="printAnswer">
          <!-- 筛选条件 -->
          <div class="searchtips" v-if="issearch">
            <div
              class="searchtips-row"
              v-for="(item, index) in siftingList"
              :key="index"
            >
              <div class="tit">问题</div>
              <el-select
                v-model="item.questionId"
                placeholder="请选择"
                @change="getoption($event, index)"
              >
                <el-option
                  v-for="e in questions"
                  :key="e.id"
                  :label="e.questionName"
                  :value="e.id"
                >
                </el-option>
              </el-select>
              <div v-if="item.options" class="tit">选项</div>
              <el-select
                class="spac"
                v-model="item.optionId"
                placeholder="请选择"
                v-if="item.questionType == 1"
              >
                <el-option
                  v-for="(o, i) in item.options"
                  :key="o.id"
                  :label="o.optionName || `选项${i + 1}`"
                  :value="o.id"
                >
                </el-option>
              </el-select>
              <el-checkbox-group
                class="spac"
                v-model="item.optionIds"
                v-if="item.questionType == 2"
              >
                <el-checkbox
                  v-for="o in item.options"
                  :label="o.id"
                  :key="o.id"
                  >{{ o.optionName }}</el-checkbox
                >
              </el-checkbox-group>
              <div
                class="searchtips-row-right spac"
                v-if="item.questionType == 3 || item.questionType == 4"
              >
                <div class="tit">关系</div>
                <el-select v-model="item.relationType" placeholder="请选择">
                  <el-option
                    v-for="t in typelist"
                    :key="t.value"
                    :label="t.label"
                    :value="t.value"
                  >
                  </el-option>
                </el-select>
                <div class="tit answertit">答案</div>
                <el-input
          v-input-restrict
                  class="spac"
                  v-model="item.answerContent"
                  placeholder="请输入内容"
                  style="width: 300px"
                ></el-input>
              </div>
              <i class="el-icon-delete spac" @click="remove(index)"></i>
            </div>
            <el-button
              style="width: 100%; margin-top: 10px"
              plain
              icon="el-icon-circle-plus"
              @click="siftingList.push({})"
              :disabled="siftingList.length == 3"
              >添加条件</el-button
            >
            <el-button
              style="margin-top: 20px"
              type="primary"
              @click="getserveyList"
              >查询</el-button
            >
          </div>
          <el-table :data="questionnaire" style="width: 100%; margin-top: 20px">
            <el-table-column type="index" label="序号" align="center">
            </el-table-column>
            <el-table-column
              prop="submitTime"
              label="提交答卷时间"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="answerDuration"
              label="所用时间"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="operate" label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="seeByid(scope.row.id, scope.$index)"
                  >详情</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="loadbtns">
            <el-button type="primary" @click="printAnswer">打印</el-button>
            <el-button type="primary" @click="loadAnswer">下载</el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 详细信息弹框 -->
    <Questionbox ref="questionbox"></Questionbox>
    <!-- 问卷信息弹框 -->
    <Answerbox ref="answerbox"></Answerbox>
  </div>
</template>

<script>
import { statistQuestion } from "../../api/questions/index";
import {
  getsurveylist,
  getquestionList,
  getoptionList,
  exportWord,
  exportExcel,
} from "../../api/questions/statistics";
import Questionbox from "./components/questionMsg.vue";
import Answerbox from "./components/answerMsg.vue";
export default {
  name: "MixedStateAdminStatistics",
  components: {
    Questionbox,
    Answerbox,
  },
  data() {
    return {
      id: "",
      questionList: [],
      types: ["单选题", "多选题", "填空题", "简答题"],
      questionnaire: [],
      survey: {},
      searchtips: [],
      issearch: false,
      questions: [],
      cheackquestion: "",
      options: [],
      cheackoption: "",
      type: undefined,
      siftingList: [
        {
          surveyId: undefined,
        },
      ],
      typelist: [
        {
          label: "等于",
          value: 1,
        },
        {
          label: "不等于",
          value: 2,
        },
        {
          label: "包含",
          value: 3,
        },
        {
          label: "不包含",
          value: 4,
        },
      ],
      test: [],
      type: undefined,
    };
  },
  created() {
    console.log(this.$route, "///");
    this.id = this.$route.query.id * 1;
    this.type = this.$route.query.surveyStatus * 1;
    if (this.type == 0) {
      this.$confirm("此问卷暂未发放，请先发放问卷。", "提示").then(() => {
        this.$router.push({
          path: `/question/index`,
        });
      });
      return;
    }
    this.siftingList[0].surveyId = this.$route.query.id;
    this.getStatist();
  },
  mounted() {
    this.getserveyList();
  },

  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "本题有效填写人次";
          return;
        }
        if (index == 1) {
          sums[index] = data[index].questionAnswerNum;
          return;
        }
        if (index == 2) {
          sums[index] = "";
          return;
        }
      });

      return sums;
    },
    lookmsg(row, idType, index) {
      this.$refs.questionbox.show(row, idType, index);
    },
    seeByid(id, index) {
      this.$refs.answerbox.show(id, index);
    },
    // 获取问卷统计信息
    async getStatist() {
      let obj = {
        surveyId: this.id,
      };
      let res = await statistQuestion(obj);
      if (!res.data) {
        this.$confirm("此问卷暂无答卷", "提示").then(() => {
          this.$router.push({
            path: `/question/index`,
          });
        });
      }
      this.survey = res.data;
    },
    // 筛选
    searchBytips() {
      this.issearch = !this.issearch;
      if (this.siftingList.length === 0) {
        this.siftingList.push({});
      }
      this.getquestion();
    },
    //  筛选获取答卷数据
    getserveyList() {
      // TODO 筛选传参
      getsurveylist(this.siftingList, this.id).then((res) => {
        this.questionnaire = res.rows;
      });
    },
    // 获取问题
    getquestion() {
      let obj = {
        surveyId: this.id,
      };
      getquestionList(obj).then((res) => {
        res.rows.forEach((e) => {
          e.questionName = e.questionName.replace(
            /<p\b[^>]*>(.*?)<\/p>/gi,
            "$1"
          );
        });
        this.questions = res.rows;
      });
    },
    // 获取选项
    async getoption(e, index) {
      let item = this.questions.find((i) => i.id === e);
      let obj = {};
      if ([1, 2].includes(item.questionType)) {
        let result = await getoptionList({
          surveyId: this.id,
          questionId: e,
        });
        obj.options = result.rows;
      }
      obj.surveyId = this.id;
      obj.questionId = e;
      obj.questionType = item.questionType;
      obj.optionIds = [];
      this.siftingList.splice(index, 1, obj);
    },
    remove(index) {
      this.siftingList.splice(index, 1);
    },
    // 下载问卷
    downLoadWord() {
      exportWord({ surveyId: this.id }).then((res) => {
        const blob = new Blob([res], { type: "" });
        let fileName = "问卷统计.docx";
        if ("download" in document.createElement("a")) {
          const link = document.createElement("a");
          link.download = fileName;
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        } else {
          navigator.msSaveBlob(blob.fileName);
        }
      });
    },
    // 打印
    printStatistics() {
      this.$html2canvas(this.$refs.printStatistics, {
        backgroundColor: "white",
        useCORS: true,
        foreignObjectRendering: false,
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight,
      }).then((canvas) => {
        const url = canvas.toDataURL();
        this.img = url;
        this.$print({
          printable: url,
          type: "image",
          documentTitle: "--",
          base64: "true",
        });
      });
    },
    // 打印答卷
    printAnswer() {
      this.$html2canvas(this.$refs.printAnswer, {
        backgroundColor: "white",
        useCORS: true,
        foreignObjectRendering: false,
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight,
      }).then((canvas) => {
        const url = canvas.toDataURL();
        this.img = url;
        this.$print({
          printable: url,
          type: "image",
          documentTitle: "--",
          base64: "true",
        });
      });
    },
    // 下载答卷
    loadAnswer() {
      exportExcel(this.siftingList, this.id).then((res) => {
        const blob = new Blob([res], { type: "" });
        let fileName = "答卷统计.xlsx";
        if ("download" in document.createElement("a")) {
          const link = document.createElement("a");
          link.download = fileName;
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        } else {
          navigator.msSaveBlob(blob.fileName);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.contrainer {
  margin: 40px;
  overflow: auto;
}
.el-tabs__item.is-top {
  font-size: 30px;
  margin-right: 100px;
}
.title {
  font-size: 25px;
  font-weight: bold;
  width: 100%;
  text-align: center;
}
.type {
  color: #adadad;
  min-width: 80px;
}
.itemtitle {
  display: flex;
  margin-bottom: 20px;
}
.item {
  margin-bottom: 30px;
}
.el-progress-bar__outer {
  height: 40px;
  border-radius: 0px !important;
}
.el-progress-bar__inner {
  height: 40px;
  border-radius: 0px !important;
}
.el-progress-bar {
  height: 40px;
  border-radius: 0px !important;
}

.loadbtns {
  position: fixed;
  bottom: 20px;
  right: 50px;
  z-index: 99;
}
.searchtips {
  padding: 20px;
  margin-top: 10px;
  background-color: #f5f5f5;
  .searchtips-row {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }
  .spac {
    margin-left: 10px;
  }

  .searchtips-row-right {
    width: 600px;
    display: flex;
    align-items: center;
  }
  .tit {
    width: 40px;
    margin-right: 10px;
    margin-left: 10px;
    font-size: 16px;
    font-weight: bold;
  }
  .answertit {
    margin-left: 15px;
    margin-right: 5px;
  }
}
.fifter {
  width: 120px;
  cursor: pointer;
}
</style>